package com.atguigu.myssm.basedao;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnUtils {

    private static ThreadLocal<Connection>  threadLocal = new ThreadLocal<>();

    public static final String DRIVER = "com.mysql.jdbc.Driver" ;
    public static final String URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true";
    public static final String USER = "root";
    public static final String PWD = "123456" ;

    public static Connection CreateConn(){
        try {
            //1.加载驱动
            Class.forName(DRIVER);
            //2.通过驱动管理器获取连接对象
            return DriverManager.getConnection(URL, USER, PWD);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return null ;
    }
    public static Connection getConn() {

        Connection connection = threadLocal.get();
        if (connection == null) {
            connection = CreateConn();
            threadLocal.set(connection);
        }
        return threadLocal.get();
    }
    public static void CloseConn() throws SQLException {

        Connection connection = threadLocal.get();
        if (connection == null) {
            return ;
        }
        if(!connection.isClosed()){
            connection.close();
            threadLocal.set(null);
        }
    }

}
